/**
 * @Author: LiMeng
 * @Date: 2017/3/20
 */
$(function () {
    var id = $(':input[name=id]').val();//用户名
    //遍历各个部门下的角色树，获取部门和角色关联数据
    var getRoleWithDeptStr = function () {
        var newRoleWithDeptArray = [];
        $('.role-tree').each(function () {
            var checked = $(this).tree('getChecked');
            if (checked.length > 0){
                var newDeptId = $(this).parent().find(':input[name=newDeptId]').val();

                var roleWithDept = $.map(checked, function (item) {
                    return newDeptId + '-' + item.id;
                });
                newRoleWithDeptArray.push(roleWithDept);
            }
        });
        return newRoleWithDeptArray.join(",");
    };

    $('#btn_save').on("click", function () {
        $.messager.progress();	// 显示进度条
        var roleWithDeptStr = getRoleWithDeptStr();

        $('#form_user').form('submit', {
            url: ROOT_PATH + '/permission/userRole/edit.shtml',
            queryParams: {
                newRoleWithDept: roleWithDeptStr
            },
            onSubmit: function (param) {
                var isValid = $(this).form('validate');
                if (!isValid) {
                    $.messager.progress('close');	// 如果表单是无效的则隐藏进度条
                }
                return isValid;	// 返回false终止表单提交
            },
            success: function (result) {
                try {
                    result = $.parseJSON(result);
                } catch (e) {
                    $.messager.progress('close');
                    parent.layer.msg(result.message, {time: 1000, icon: 2});
                }
                if (result.success) {
                    $.messager.progress('close');	// 如果提交成功则隐藏进度条
                    parent.layer.msg(result.message, {time: 1000, icon: 1}, function () {
                        parent.$('#dg1').datagrid('load');
                        parent.layer.closeAll(); //先得到当前iframe层的索引
                    });
                } else {
                    $.messager.progress('close');	// 如果提交失败则不做处理
                    parent.layer.msg(result.message, {time: 1000, icon: 2});
                }
            }
        });
    });
    $('#btn_clear').on("click", function () {
        $('.role-tree').each(function () {
            var checked = $(this).tree('getChecked');
            if (checked.length > 0) {
                for (var i = 0; i < checked.length; i++) {
                    var obj = checked[i];
                    $(this).tree('uncheck', obj.target);
                }
            } else {
                return false;
            }
        });
    });
});